'use strict'

import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfo, logout } from '@api/user'
import store from "@utils/store/cookie"

const LOGIN_KEY = "login_status"

Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    token: store.get(LOGIN_KEY) || null,
    userInfo: null
  },
  // getters 相当于 Store 的计算属性
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo
  },
  // mutations 必须是同步函数
  mutations: {
    UPDATE_USERINFO (state, userInfo) {
      state.userInfo = userInfo || null
    },
    LOGIN(state, token, expiresTime) {
      state.token = token
      store.set(LOGIN_KEY, token, expiresTime)
    },
    LOGOUT(state) {
      state.token = null
      state.userInfo = null
      store.remove(LOGIN_KEY)
    }
  },
  // actions 可以是异步函数
  actions: {
    USERINFO ({ commit }, force) {
      getUserInfo().then(res => {
        commit("UPDATE_USERINFO", res.data)
        // reslove(res.data)
      }).catch(err => {
        console.log(err)
      })
    },
    LOGOUT ({ commit }) {
      logout().then(res => {
        commit("LOGOUT")
      }).catch(err => {
        console.log('logout err', err)
      })
    }
  },
  modules: {
  }
})
